package com.cs.bd.ad.params;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

import com.cs.bd.ad.AdSdkApi;

public class ClientParams {

    static final String KEY_BUY_CHANNEL = "buyChannel";
    static final String KEY_INSTALL_TIME = "installTime";
    static final String KEY_IS_UPGRADE = "isUpgrade";
    static final String KEY_USE_FROM = "user_from";
    private String mBuyChannel;
    private long mInstalledTime;
    private boolean mIsUpgrade;
    private String mUseFrom;

    public ClientParams setUseFrom(String useFrom) {
        this.mUseFrom = useFrom;
        return this;
    }

    public ClientParams(String buyChannel, long installTime, boolean isUpgrade) {
        this.mBuyChannel = buyChannel;
        this.mInstalledTime = installTime;
        this.mIsUpgrade = isUpgrade;
    }

    public String getUseFrom() {
        return this.mUseFrom;
    }

    public String getBuyChannel() {
        return this.mBuyChannel;
    }

    public long getInstalledTime() {
        return this.mInstalledTime;
    }

    public int getCDays(Context context) {
        return this.mInstalledTime > 1L ? AdSdkApi.calculateCDays(context, this.mInstalledTime) : 1;
    }

    public boolean getIsUpgrade() {
        return this.mIsUpgrade;
    }

    public static void save2Local(Context context, ClientParams param) {
        if (param != null) {
            SharedPreferences sp = getSP(context);
            sp.edit().putString("buyChannel", param.getBuyChannel()).putLong("installTime", Math.max(1L, param.getInstalledTime())).putBoolean("isUpgrade", param.getIsUpgrade()).putString("user_from", param.mUseFrom).commit();
        }

    }

    public static ClientParams getFromLocal(Context context) {
        SharedPreferences sp = getSP(context);
        String buyChannel = sp.getString("buyChannel", (String)null);
        long installTime = sp.getLong("installTime", 1L);
//        if (installTime <= 1L) {
//            long[] ti = AppUtils.getPkgTimeInfo(context, context.getPackageName());
//            installTime = ti != null ? ti[0] : installTime;
//        }

        boolean isUpgrade = sp.getBoolean("isUpgrade", false);
        String useFrom = sp.getString("user_from", (String)null);
        return !TextUtils.isEmpty(useFrom) ? (new ClientParams(buyChannel, installTime, isUpgrade)).setUseFrom(useFrom) : new ClientParams(buyChannel, installTime, isUpgrade);
    }

    static SharedPreferences getSP(Context context) {
        return context.getSharedPreferences("adsdk_client_params", 0);
    }

}
